﻿@using System.Linq;
@using System.Collections.Generic;
@using DCMS.Web.Extensions;
@using DCMS.Web.Framework.UI;
@using DCMS.ViewModel.Models.Visit;

@model LineTierListModel

<section id="content_wrapper">

    <!-- Start: Topbar-Dropdown -->
    <div id="topbar-dropmenu">
        <div id="topbar-dropmenu">
            @await Html.PartialAsync("_ToolBox")
        </div>
    </div>
    <!-- End: Topbar-Dropdown -->
    <!-- Start: Topbar -->
    <header id="topbar">
        <div class="topbar-left">
            <ol class="breadcrumb">
                <li class="crumb-active">
                    <a href="@Url.RouteUrl("HomePage")">档案管理</a>
                </li>
                <li class="crumb-icon">
                    <a href="@Url.RouteUrl("HomePage")">
                        <span class="glyphicon glyphicon-home"></span>
                    </a>
                </li>
                <li class="crumb-link">
                    <a href="#">员工相关</a>
                </li>
                <li class="crumb-trail">分配线路设置</li>
            </ol>
        </div>
        <div class="topbar-right">
            <div class="ml15 ib va-m" id="toggle_sidemenu_r">
                <a href="#" class="pl5">
                    <i class="fa fa-sign-in fs22 text-primary"></i>
                    <span class="badge badge-hero badge-danger">3</span>
                </a>
            </div>
        </div>
    </header>
    <!-- End: Topbar -->
    <!-- Begin: Content -->
    <section id="content">
        <div class="row">
            <div class="col-md-2">
                <div class="panel">
                    <div class="panel-heading">
                        <div class="pull-left">
                            业务员
                        </div>
                        <div class="pull-right">
                        </div>
                    </div>
                    <div class="panel-body">
                        <div id="tree"> </div>
                    </div>
                </div>
            </div>
            <div class="col-md-10">
                @*Toolbar*@
                <div class="row mb10">
                    <div class="col-md-11"></div>
                    <div class="col-md-1">
                        <button class="btn btn-primary btn-block" type="button" id="FormSubmit" value="保存"><i class="fa fa-floppy-o mr5"></i>保存</button>
                    </div>
                </div>

                @*GridView*@
                <div class="panel">
                    <div class="panel-heading">
                        <span class="panel-title">
                            <span class="glyphicon glyphicon-th"></span>线路分配
                        </span>
                    </div>
                    <div class="panel-body p5">
                        <table id="userLineTierAssign" class="table table-striped table-bordered table-hover"></table>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!-- End: Content -->
    <input id="hid_userId" type="hidden" value="" />
</section>


@{ await Html.RenderPartialAsync("_ModalForm", new ViewDataDictionary(ViewData) { { "modalWindow", "modal-form-lineTier" }, { "formId", "ModalForm" }, { "windowWidth", "680px" }, { "showSave", "true" } }); }


@section CurPageScripts
{

    <script type="text/javascript">
        jQuery(document).ready(function () {
            "use strict";
            // Init Theme Core
            Core.init({
                sbm: "sb-l-c",
            });
            // Init Demo JS
            Demo.init();

            //左侧线路类别树
            $("#tree").fancytree({
                extensions: ["dnd", "edit"],
                //titlesTabbable: true,
                debugLevel: 2,
                source: toTree(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.BusinessUsers))),
                dnd: {
                    autoExpandMS: 400,
                    focusOnClick: true,
                    preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
                    preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
                    dragStart: function (node, data) { return true; },
                    dragEnter: function (node, data) { return true; },
                    dragDrop: function (node, data) { data.otherNode.moveTo(node, data.hitMode); }
                },
                activate: function (event, data) {
                    //alert("activate " + data.node);
                },
                lazyLoad: function (event, data) {
                    //data.result = [{ "title": "Sub item", "lazy": true }, { "title": "Sub folder", "folder": true, "lazy": true }]
                    //[{ "title": "Sub item", "lazy": true }, { "title": "Sub folder", "folder": true, "lazy": true }]
                },
                click: function (event, data) {
                    $("#hid_userId").val(data.node.key);
                    $("#userLineTierAssign").bootstrapTable('refresh', { url: "/LineTier/UserLineTierAssignList", silent: true, query: { userId: data.node.key} });
                }
            });
            //数组转树结构
            function toTree(data) {
                var newdata = [{ title: "业务员名称", key: -1, pid: 0, expanded: true, folder: true }];
                data.forEach(function (item) {
                    var tempdata = { title: item.UserRealName, key:item.Id, pid: -1, expanded: true, folder: false };
                    newdata.push(tempdata);
                });

                // 删除 所有 children,以防止多次调用
                newdata.forEach(function (item) {
                    delete item.children;
                });
                // 将数据存储为 以 id 为 KEY 的 map 索引数据列
                var map = {};
                newdata.forEach(function (item) {
                    map[item.key] = item;
                });
                //        console.log(map);
                var val = [];
                newdata.forEach(function (item) {
                    // 以当前遍历项，的pid,去map对象中找到索引的id
                    var parent = map[item.pid];
                    // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
                    if (parent) {
                        var temp = (parent.children || (parent.children = []));
                        temp.push(item);
                        if (temp.length > 0) parent.folder = true;
                    } else {
                        //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
                        item.folder = true;
                        val.push(item);
                    }
                });
                return val;
            }

            $("#userLineTierAssign").bootstrapTable({
               @Html.Raw(Model.UserLineTierAssigns.Count > 0 ? "url: '/LineTier/UserLineTierAssignList?userId=0'," : "length: 9,")
                striped: true,
                cache: false,
                pagination: true,
                showPagination: false,
                sidePagination: "server",
                sortable: false,
                sortOrder: "asc",
                search: false,
                strictSearch: false,
                showColumns: false,
                showRefresh: false,
                clickToSelect: false,
                uniqueId: "id",
                showToggle: false,
                editable: true,
                cardView: false,
                detailView: false,
                showFooter: false,
                onLoadSuccess: function (data) {
                    $(".fixed-table-pagination").hide();
                    //return {
                    //    "data": data.rows
                    //};
                },
                columns: [
                    { title: '<i class="fa fa-gear fs18"></i>', align: 'center', width: '60', formatter: function (value, row, index) {
                            return m_pagerow + index + 1;
                        }
                    },
                    {
                        field: 'Order', title: '线路顺序', align: 'center', width: '80',
                        formatter: $(this).formatIsNull},
                    { field: 'LineTierId', visible: false },
                    {
                        field: 'LineTierName', title: '线路名称', class: 'editable', align: 'left', width: '480',
                        formatter: $(this).formatIsNull},
                    {
                        field: 'Quantity', title: '终端数量',
                        formatter: $(this).formatIsNull},
                    { field: 'Operate', title: '操作', align: 'center', width: '100',
                        events: {
                            'click .rowAppend': function (e, value, row, index) {// 添加
                                //var len = $('#userLineTierAssign').bootstrapTable('getData').length;
                                //var data = { Id: len + 1, Amount: 0, Remark: "" };
                                //var that = $('#userLineTierAssign').bootstrapTable('append', data);
								var newrow = {};
                                $('#userLineTierAssign').bootstrapTable('insert', newrow);
                            },
                            'click .rowDel': function (e, value, row, index) {// 删除
                                if (row.LineTierId >= 0 && row.Id != 0) {
                                    WinMsg.confirm({ message: "确认要删除选择的数据吗？" }).on(function (e) {
                                        if (!e) {
                                            return;
                                        }
                                        $(this).remoteSubmit("post", "/LineTier/DeleteUserLineTierAssign", { userLineTierAssignId: row.Id }, null, function () {
                                            $("#userLineTierAssign").bootstrapTable('remove', { field: "id", values: [parseInt(row.Id)] });
                                            $("#userLineTierAssign").bootstrapTable('refresh', { url: "/LineTier/UserLineTierAssignList", silent: true, query: { userId: $("#hid_userId").val() } });
                                        });
                                    });
                                }
                                else {
                                    if (row.uniqueid == undefined) {
                                        $("#userLineTierAssign").bootstrapTable('remove', { field: "id", values: [parseInt(row.Id)] });
                                    }
                                    else {
                                        $("#userLineTierAssign").bootstrapTable('remove', { field: "uniqueid", values: [parseInt(row.uniqueid)] });
                                    }
                                }

                            }
                        },
                        formatter: function (value, row, index) {
                            return [
                                '<button type="button" class="btn btn-sm btn-default rowAppend" title="添加"><i class="fa fa-plus" ></i></button>',
                                '<button type="button" class="btn btn-sm btn-default rowDel" title="删除"><i class="fa fa-trash-o"></i></button>'
                            ].join('');
                        }
                    }
                ],
				onClickCell: function (field, value, row, $element) {

					if (field == "Operate") {
						return false;
					}

                    var input = $($element).find("input");
                    var select = $($element).find("select");
                    if (input.length > 0 || select.length > 0)
                        return false;

                    //当前列所在行的索引
                    var index = $element.parent().attr("data-index");
                    //console.log(index);

                    if (field == "LineTierName") {
                        var html = '';
                        html += '<select id="select_' + field + "_" + row.Id + '"><option value="">-请选择线路-</option>'
						var lineTiers = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.LineTiers));
						lineTiers.forEach(function (item) {
                            html += '<option value="' + item.Id + '" qty="' + item.Qty + '">' + item.Name + '</option>';
                        });
                        html += '</select>';

                        $($element).html(html);
                        var inputObj = $("#select_" + field + "_" + row.Id);
                        inputObj.focus();
						inputObj.bind("focusout", function () {
                            var lineTierId = $(this).val();
                            var lineTierName = "";
                            var quantity = 0;
                            if (lineTierId != "") {
                                lineTierName = $(this).find("option:selected").text();
                                quantity = $(this).find("option:selected").attr("qty");
                            }
                            $("#userLineTierAssign").bootstrapTable('updateRow', { index: index, row: { LineTierId: lineTierId, LineTierName: lineTierName, Quantity: quantity } });
                            $($element).html("" + value + "");
                        });
                    }
                     else if (field == "Order") {
                        var html = '<input type="text" class="form-control input-sm" value="' + (typeof (value) == 'undefined' ? "" : value) + '" id="' + field + "_" + row.Id + '">';
                        $($element).html(html);
                        var inputObj = $("#" + $(html).attr("id"));
                        inputObj.focus();
                        inputObj.bind("focusout", function () {
                            $("#userLineTierAssign").bootstrapTable('updateRow', { index: index, row: { Order: $(this).val() } });
                            $($element).html("" + value + "");
                        });
                    }
                    //debug
                    $.each($('#userLineTierAssign').bootstrapTable('getData'), function (i, row) {
                        //console.log(row);
                    });
                }
            });

            //保存业务员分配线路
            $("#FormSubmit").click(function () {
                if ($("#hid_userId").val() == "") {
                    $(this).showToastr("请选择业务员");
                    return false;
                }
                var flag = false;
                //获取表格的所有内容行
                var serializeData = [];
                $.each($('#userLineTierAssign').bootstrapTable('getData'), function (i, row)
                {
                    var tmpObj = {
                        "Id": typeof (row.Id) == 'undefined' ? "0" : row.Id,
                        "UserId": $("#hid_userId").val(),
                        "LineTierId": typeof (row.LineTierId) == 'undefined' ? "0" : row.LineTierId,
                        "Order": typeof (row.Order) == 'undefined' ? "0" : row.Order
                    };
                    if (typeof (row.LineTierId) != 'undefined')
                        serializeData.push(tmpObj);
                });
                 //保存的数据
				var postData = {
					Items: serializeData
				};
                //console.log(JSON.stringify(serializeData));
                $(this).remoteSubmit("post", "/LineTier/UpdateUserLineTierAssigns?userId=" + $("#hid_userId").val(), postData, null, function () {
                    $("#lineTierOption").bootstrapTable('refresh', { url: "/LineTier/UserLineTierAssignList", silent: true, query: { userId: $("#hid_userId").val() } });
                });

            });
        });
    </script>
}